package com.kaishengit.util;
import java.sql.*;
import java.util.*;
public class DBHelp<T> {
	private final static String DRIVER="com.mysql.jdbc.Driver";
	private final static String URL="jdbc:mysql:///mydb";
	private final static String USER="root";
	private final static String PWD="root";
	
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() throws SQLException{
		return DriverManager.getConnection(URL,USER,PWD);
	}
	
	public T executeQueryForObject(String sql,RowMapper<T> rm,Object... args){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		T t=null;
		try {
			conn=getConnection();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i+1, args[i]);
			}
			rs=ps.executeQuery();
			if(rs.next()){
				t=rm.mapRow(rs);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(rs, ps, conn);
		}
		return t;
	}
	
	public List<T> executeQueryForList(String sql,RowMapper<T> rm,Object... args){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		List<T> list=new ArrayList<T>();
		try {
			conn=getConnection();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i+1, args[i]);
			}
			rs=ps.executeQuery();
			while(rs.next()){
				T t=rm.mapRow(rs);
				list.add(t);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(rs, ps, conn);
		}
		return list;
	}
	
	public boolean executeSQL(String sql,Object... args){
		Connection conn=null;
		PreparedStatement ps=null;
		
		try {
			conn=getConnection();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i+1, args[i]);
			}
			int num=ps.executeUpdate();
			if(num>0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(ps, conn);
		}
		return false;		
	}
	
	public void close(ResultSet rs,PreparedStatement ps,Connection conn){
		try {
			if(rs!=null){
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(ps!=null){
					ps.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					if(conn!=null){
						conn.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void close(PreparedStatement ps,Connection conn){
		close(null,ps, conn);
	}
	
}
